package org.beetl.json.node;

import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Method;

import org.beetl.json.AbstractOutputNode;
import org.beetl.json.Location;
import org.beetl.json.loc.TypeLocation;
import org.beetl.json.util.JsonUtil;
import org.beetl.json.util.MethodInvoker;

public class AttributeNode extends AbstractOutputNode {

	private Class c;
	private String attrName;
	private Class attrType;
	MethodInvoker methodProxy = null;
	public AttributeNode(Class c,Method m){
		this.c = c ;
		this.attrType = m.getReturnType();
		this.attrName = JsonUtil.getAttribute(m);
		methodProxy = new MethodInvoker(m);
	
	}
	@Override
	public  void render(Object obj,Writer w,String after) throws IOException{
		
		String key = attrName;
		String value= null;
		
		if(this.keyAction!=null){
			
			Object keyValue = keyAction.doit(obj, this);
			if(keyValue==null) return ;
			key = keyValue.toString();
		}
		
	
		Object attrValue = methodProxy.invoke(obj);
		if(this.valueAction!=null){
			attrValue = valueAction.doit(attrValue, this);		
			
		}
		//how to change attrName?new action
		w.write(key);
		w.write(":");
		w.write(attrValue.toString());	
		w.write(after);

	}
	@Override
	protected boolean isMatch(Location location) {
		return location.match(this.attrType, this.attrName);
	}


	

}
